package storage

import (
	"context"
	"sync"
	"time"

	"github.com/it-sos/golibs/db/redis"
)

type redisDb struct {
	db redis.GoLibRedis
}

func (a redisDb) GetExpire(key string) (time.Duration, error) {
	return a.db.TTL(context.Background(), key).Result()
}

func (a redisDb) Get(key string) (string, error) {
	return a.db.Get(context.Background(), key).Result()
}

func (a redisDb) Remove(key string) error {
	return a.db.Del(context.Background(), key).Err()
}

func (a redisDb) Lock(key string, duration time.Duration) (bool, error) {
	return a.db.SetNX(context.Background(), key, true, duration).Result()
}

func (a redisDb) Set(key, value string, duration time.Duration) error {
	return a.db.Set(context.Background(), key, value, duration).Err()
}

var instRedis Storage
var onceRedis sync.Once

func storeRedis() Storage {
	onceRedis.Do(func() {
		instRedis = &redisDb{
			redis.NewRedis(),
		}
	})
	return instRedis
}
